<template>
  <div id="inventory_detail" style="height:100%" v-loading="loading">
    <v-tableTitle :btnConfig="btnConfig" @download="download"
                  @handleDownTemplate="downloadExcelFile" @handleDownErrorFile="exceptionFileUrl"></v-tableTitle>
    <GTable class="base-grid" :hasCheck="true" :hasEdit="true" v-model="gridObj" :defaultColDef="defaultColDef"
      :highlightCurrentRow="false" :disabled="true" :rules="rules" :otherHeight="80" :tmsShowFilter="true"
      :columnConfig="columnConfig" api="queryVibdetailList" :extraColumns="extraColumns" :showSummary="false"
      :pagination="true" @selection-change="handleSelectionChange" @setdialog="setdialog"
      @filter-changed="filterChanged" @cell-dblclick="cellDblclick" @grid-ready="agGridReady">
    </GTable>
    <el-drawer :title="$t('ex.invSernumInventory')" :visible.sync="dialogFlag" direction="rtl" size="60%"
      destroy-on-close>
      <router-view></router-view>
    </el-drawer>
  </div>
</template>

<script>
import baseMixin from "@/mixins/BaseMixin";
import agGridBaseMixin from "@/mixins/AgGridBaseMixin";

export default {
  name: "inventory_detail",
  mixins: [baseMixin, agGridBaseMixin],
  props: {
    inputData: {
      type: Object
    }
  },
  data() {
    return {
      height: 0,
      title: this.$t('ex.inventory_detail'),
      downloading: false,
      dialogFlag: false,
      columnConfig: { menu_id: 66, menu_code: "vibdetail", menu_list_code: "InventoryDetail", },
      filterParams: {},
      selectData: [],
      defaultColDef: {
      },
    };
  },
  computed: {
    btnConfig() {
      return [
        { label: this.$t('common.export'), certigier: !this.btnPermNameList.includes('WM06020801'), invalid: "download", loading: this.downloading },
        { type: "file", certigier: !this.btnPermNameList.includes('WM06020805'), label: this.$t('work.openingInventoryImport'), invalid: "file",importType: '10323', importUrl: "importOpeningInventory", downTemplate: "handleDownTemplate", sheetKey: "openingInventorySerialList" }
      ]
    }
  },
  watch: {
    $route(data) {
      if (data.name === "invSernumInventoryDeawer") {
        this.dialogFlag = true;
      } else {
        this.dialogFlag = false;
      }
    },
  },
  methods: {
    //设置弹框
    setdialog(data) {
      this.$store.commit("setRouteData", data);
      this.dialogFlag = true;
      this.$nextTick(() => {
        this.$router.push({ name: "invSernumInventoryDeawer" });
      });
    },
    filterChanged(param) {
      this.filterParams = param.api.getFilterModel()
    },
    handleSelectionChange(data) {
      this.selectData = data
    },
    download() {
      const { menu_list_code: menuListCode, menu_code: menuCode } = this.columnConfig;
      const excelName = this.title;
      if (menuListCode && menuCode && excelName) {
        let params = []
        if (!this._.isEmpty(this.filterParams)) {
          let obj = {}
          Object.keys(this.filterParams).forEach(key => {
            obj[key] = this.filterParams[key].filter
          })
          params = [obj]
        }
        if (!this._.isEmpty(this.selectData)) {
          params = this.selectData
        }
        this.downloading = true;
        this.$download({ menuCode, menuListCode, name: excelName }, params).then(res => {
          this.downloading = false;
        }).finally(() => {
          this.downloading = false;
        })
      }
    },
    async getTableData(page, data) {
      this.$set(data, "pageNum", page);
      this.$set(data, "pageSize", this.pageSize);
      try {
        this.loading = true;
        let res = await this.$api.post(`/queryVibdetailList`, data);
        
          this.rowData = res.page.list;
          this.page = res.page.curpage;
          this.pageSize = res.page.pageSize;
          this.total = res.page.total;
        
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.loading = false;
      }
    },
    exceptionFileUrl(exceptionUrl) {

      console.log("exceptionFileUrl = %o", exceptionUrl);
      const data = [{
        exceptionFileUrl: exceptionUrl
      }];

      // 异常下载配置
      let urlConf = { responseType: 'blob' };
      let exceptionFileName = "期初库存导入模板异常文件.xls";
      let url = '/comExcelImportResult/downloadExceptionFile';
      let options = { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8' };

      try {
        this.$api.post(url, data, urlConf).then(res => {
          let blobParts = [res.data];
          if (window.navigator.msSaveBlob) {
            const blobObject = new Blob(blobParts);
            window.navigator.msSaveBlob(blobObject, exceptionFileName);
          } else {
            let tagName = 'a';
            const blob = new Blob(blobParts, options);
            const downloadElement = document.createElement(tagName);
            // 创建下载的链接
            const href = window.URL.createObjectURL(blob);
            downloadElement.style.display = 'none';
            downloadElement.href = href;
            // 下载后文件名
            downloadElement.download = exceptionFileName;
            document.body.appendChild(downloadElement);
            // 点击下载
            downloadElement.click();
            // 下载完成移除元素
            document.body.removeChild(downloadElement);
            // 释放掉blob对象
            window.URL.revokeObjectURL(href);
          }
        });
      } catch (e) {
        this.$message.error(e);
      }
    },
    async downloadExcelFile() {
      try {
        let xlsName = "期初库存导入模板.xls";
        let url = "/downloadExcelFile/" + xlsName;
        let res = await this.$api.post(url, {}, { responseType: 'blob' })
        if (window.navigator.msSaveBlob) {
          var blobObject = new Blob([res.data]);
          window.navigator.msSaveBlob(blobObject, xlsName);
        } else {
          var blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8' });
          var downloadElement = document.createElement('a');
          var href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.style.display = 'none';
          downloadElement.href = href;
          downloadElement.download = xlsName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }
      } catch (e) {
        this.$message.error(e);
      }
    },
  },
  mounted() {
    this.$store.commit("setSkip", {});
    this.$store.commit("setRouteId", "");
    this.$store.commit("setNewFlag", false);
    this.$store.commit("setRouteData", {});
    // this.getTableData(1, {});
  },
};
</script>

<style scoped>
#inventory_detail {
  width: 100%;
  height: 99%;
}
</style>
